<template>
  <el-container style="height: 100vh;">
    <!-- 左侧导航栏 -->
    <el-aside :width="sideWidth + 'px'" style="background-color: rgb(238, 241, 246)">
      <Sidebar />
    </el-aside>

    <!-- 右侧内容 -->
    <el-container>
      <!-- 页面头部 -->
      <el-header style="background-color: #409EFF; padding: 10px; color: white">
        <div style="display: flex; align-items: center">
          <!-- 头像 -->
          <el-avatar
              size="60"
              src=""
              alt="头像"
              style="margin-right: 20px"
          />
          <!-- 用户信息 -->
          <div>
            <h2 style="margin: 0; font-size: 24px">张三</h2>
            <p style="margin: 0; font-size: 16px">牛马大学生</p>
          </div>
        </div>
      </el-header>

      <!-- 页面主体 -->
      <el-main style="padding: 20px">
        <el-card shadow="always" style="margin-top: 30px;">
          <!-- 搜索框 -->
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="练习名称">
              <el-input v-model="searchName" placeholder="请输入练习名称"></el-input>
            </el-form-item>
            <el-form-item label="当前状态">
              <el-select v-model="searchStatus" placeholder="请选择">
                <el-option label="未开始" value="未开始"></el-option>
                <el-option label="进行中" value="进行中"></el-option>
                <el-option label="已结束" value="已结束"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否已经提交">
              <el-select v-model="searchSubmitted" placeholder="请选择">
                <el-option label="已提交" value="y"></el-option>
                <el-option label="未提交" value="n"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
            </el-form-item>
          </el-form>

          <!-- 表格 -->
          <el-table
              :data="filteredExerciseList"
              style="width: 100%"
              border
              row-key="id"
          >
            <el-table-column
                prop="name"
                label="练习名称"
                width="250"
                align="center"
            />
            <el-table-column
                label="当前状态"
                width="250"
                align="center"
            >
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row)" class="status-tag">
                  {{ getStatusText(scope.row) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
                label="是否已经提交"
                width="250"
                align="center"
            >
              <template #default="scope">
                <el-tag :type="getSubmitTagType(scope.row.isSubmit)" class="status-tag">
                  {{ getSubmitText(scope.row.isSubmit) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
            >
              <template #default="scope">
                <div class="action-buttons">
                  <el-button
                      :disabled="!isStartable(scope.row)"
                      type="text"
                      class="action-button"
                      @click="startExercise(scope.row)"
                  >
                    开始练习
                  </el-button>
                  <el-button
                      :disabled="!isViewable(scope.row)"
                      type="text"
                      class="action-button view-details-button"
                      @click="viewDetails(scope.row)"
                  >
                    查看详情
                  </el-button>
                  <el-button
                      type="text"
                      class="action-button delete-button"
                      @click="deleteExercise(scope.row)"
                  >
                    删除
                  </el-button>
                  <!-- 在操作列中新增一个按钮 -->
                  <el-button
                      :disabled="!isViewable(scope.row)"
                      type="text"
                      class="action-button view-accuracy-button"
                      @click="viewAccuracy(scope.row)"
                  >
                    查看正确率
                  </el-button>
                  <!-- 添加正确率弹窗 -->
                  <el-dialog
                      title=""
                      v-model="accuracyDialogVisible"
                      width="50%"
                      append-to-body
                  >
                    <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
                    <div style="margin-top: 20px; text-align: center; font-size: 18px; line-height: 1.6">
                      {{ accuracyTips }}
                    </div>
                  </el-dialog>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 分页 -->
        <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="exerciseList.length"
            :page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            style="margin-top: 20px; text-align: center;"
        />
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { ElMessage, ElMessageBox } from "element-plus";
import Sidebar from "@/views/Sidebar.vue";
import axios from "axios";
import * as echarts from 'echarts';

export default {
  components: {
    Sidebar,
  },
  data() {
    return {
      sideWidth: 200, // 侧边栏宽度
      exerciseList: [], // 练习列表
      searchName: "", // 搜索名称
      searchStatus: "", // 搜索状态
      searchSubmitted: "", // 搜索是否提交
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示条数
      HomeworkList: [],
      accuracyDialogVisible: false,
      chapterAccuracy: [],
      chartInstance: null, // 用于存储 ECharts 实例
      accuracyTips: "" // 提示信息
    };
  },
  computed: {
    filteredExerciseList() {
      return this.exerciseList
          .filter(item => {
            const nameMatch = this.searchName === "" || item.name.includes(this.searchName);
            const statusMatch =
                this.searchStatus === "" || this.getStatusText(item) === this.searchStatus;
            const submittedMatch =
                this.searchSubmitted === "" || item.isSubmit === this.searchSubmitted;
            const isUseMatch = item.isUse === 'y'; // 确保 isUse 为 'y'
            return nameMatch && statusMatch && submittedMatch && isUseMatch;
          })
          .slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    }
  },
  mounted() {
    this.getExerciseList();
  },
  methods: {
    handlePageChange(page) {
      this.currentPage = page;
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1; // 重置到第一页
    },
    getExerciseList() {
      axios.get("http://localhost:80/students/getExerciseList").then((resp) => {
        const result = resp.data;
        this.exerciseList = result.data.map(item => ({
          ...item,
          status: this.getStatusText(item),
          submitted: this.getSubmitText(item.isSubmit)
        }));
      });
    },
    getStatusTagType(row) {
      switch (this.getStatusText(row)) {
        case "未开始":
          return "info";
        case "进行中":
          return "warning";
        case "已结束":
          return "success";
        default:
          return "";
      }
    },
    getSubmitTagType(submitted) {
      return submitted === "y" ? "success" : "danger";
    },
    getStatusText(row) {
      const now = new Date();
      const startTime = new Date(row.start_time);
      const endTime = new Date(row.end_time);

      if (now > endTime) {
        return "已结束";
      } else if (now >= startTime && now <= endTime) {
        return "进行中";
      } else {
        return "未开始";
      }
    },
    getSubmitText(isSubmit) {
      return isSubmit === "y" ? "已提交" : "未提交";
    },
    isAfterEndTime(row) {
      const now = new Date();
      const endTime = new Date(row.end_time);
      return now > endTime;
    },
    isInProgress(row) {
      const now = new Date();
      const startTime = new Date(row.start_time);
      const endTime = new Date(row.end_time);
      return now >= startTime && now <= endTime;
    },
    isStartable(row) {
      // 如果已经提交，则不可开始练习
      if (row.isSubmit === "y") return false;
      return this.isInProgress(row);
    },
    isViewable(row) {
      return this.isAfterEndTime(row) || row.isSubmit === 'y';
    },
    viewDetails(row) {
      if (this.isViewable(row)) {
        console.log(`查看详情: ${row.name}`);
        ElMessage.success(`查看详情: ${row.name}`);
        this.$router.push({
          path: '/questions/detail',
          query: { id: row.id }
        });
      } else {
        ElMessage.warning("无法查看详情");
      }
    },
    deleteExercise(row) {
      ElMessageBox.confirm(`确定要删除练习 "${row.name}" 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            // 调用后端删除接口
            axios.get("http://localhost:80/assignments/delete", {
              params: {
                ass_id: row.id
              }
            })
                .then((response) => {
                  if (response.data.code === 0) {
                    // 删除成功，更新本地数据
                    const index = this.exerciseList.findIndex(item => item.id === row.id);
                    if (index !== -1) {
                      this.exerciseList.splice(index, 1);
                      ElMessage.success("删除成功");
                    }
                  } else {
                    ElMessage.error("删除失败");
                  }
                })
                .catch((error) => {
                  console.error("删除请求失败:", error);
                  ElMessage.error("删除请求失败");
                });
          })
          .catch(() => {
            ElMessage.info("已取消删除");
          });
    },
    startExercise(row) {
      if (this.isStartable(row)) {
        console.log(`开始练习: ${row.name}`);
        console.log(row.id);
        // 使用查询参数传递 id
        this.$router.push({
          path: '/questions/exercise',
          query: { id: row.id }
        });
      } else {
        ElMessage.warning("无法开始练习");
      }
    },
    handleSearch() {
      this.currentPage = 1; // 重置为第一页
    },
    viewAccuracy(row) {
      axios.get(`http://localhost:80/questions/analysis/${row.id}`)
          .then(response => {
            // 格式化数据
            this.chapterAccuracy = response.data.map((item, index) => ({
              chapter: `第${index + 1}章`, // 将索引转换为章节编号
              accuracy: parseFloat(item.accuracy).toFixed(2) // 保留两位小数
            }));
            this.accuracyDialogVisible = true;
            this.$nextTick(() => {
              this.initChart();
              this.accuracyTips = this.getAccuracyTips(); // 获取提示信息
            });
          })
          .catch(error => {
            console.error("获取正确率数据失败:", error);
            ElMessage.error("获取正确率数据失败");
          });
    },
    // 新增的初始化图表方法
    initChart() {
      if (this.chartInstance) {
        this.chartInstance.dispose(); // 销毁之前的实例
      }
      this.chartInstance = echarts.init(this.$refs.chartContainer);
      const option = {
        title: {
          text: '章节正确率',
          left: 'center',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}%'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.chapterAccuracy.map(item => item.chapter)
        },
        series: [
          {
            name: '正确率',
            type: 'pie',
            radius: '50%',
            data: this.chapterAccuracy.map(item => ({
              name: item.chapter,
              value: parseFloat(item.accuracy) // 转换为数字
            })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      this.chartInstance.setOption(option);
    },
    getAccuracyTips() {
      if (!this.chapterAccuracy || this.chapterAccuracy.length === 0) {
        return "";
      }
      if (this.chapterAccuracy.length === 1) {
        const onlyChapter = this.chapterAccuracy[0];
        return `${onlyChapter.chapter}正确率为${onlyChapter.accuracy}%，还需加强学习！`;
      }
      // 找到正确率最低的章节
      let minAccuracyChapter = this.chapterAccuracy[0];
      for (let i = 1; i < this.chapterAccuracy.length; i++) {
        if (parseFloat(this.chapterAccuracy[i].accuracy) < parseFloat(minAccuracyChapter.accuracy)) {
          minAccuracyChapter = this.chapterAccuracy[i];
        }
      }
      // 找到正确率最高的章节
      let maxAccuracyChapter = this.chapterAccuracy[0];
      for (let i = 1; i < this.chapterAccuracy.length; i++) {
        if (parseFloat(this.chapterAccuracy[i].accuracy) > parseFloat(maxAccuracyChapter.accuracy)) {
          maxAccuracyChapter = this.chapterAccuracy[i];
        }
      }
      return `${minAccuracyChapter.chapter}正确率最低,还需加强;${maxAccuracyChapter.chapter}正确率最高,继续保持!`;
    }
  },
  beforeUnmount() {
    if (this.chartInstance) {
      this.chartInstance.dispose(); // 组件销毁时清理图表实例
    }
  }
};
</script>

<style scoped>
/* 分页样式 */
.el-pagination {
  margin-top: 20px;
  text-align: center;
}

/* 表格整体样式 */
.exercise-table {
  width: 100%;
}

/* 表头和内容对齐 */
.el-table th {
  text-align: center !important;
  background-color: #f5f7fa;
  font-size: 16px;
  padding: 12px 0;
}

.el-table td {
  text-align: center !important;
  font-size: 16px;
  padding: 12px 0;
}

/* 操作按钮样式 */
.action-button {
  font-size: 16px !important;
  padding: 8px 16px !important;
  margin: 0 8px !important;
  cursor: pointer;
}

.action-button:disabled {
  background-color: #c0c4cc !important;
  color: #fff !important;
  cursor: not-allowed;
}

.view-details-button:disabled {
  background-color: #c0c4cc !important;
  color: #fff !important;
}

.delete-button {
  background-color: #ff4d4f !important;
  color: #fff !important;
}

/* 状态标签样式 */
.status-tag {
  font-size: 16px !important;
  padding: 8px 16px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
}

/* 确保按钮之间的间距 */
.el-button + .el-button {
  margin-left: 10px;
}

/* 确保标签居中显示 */
.el-tag {
  display: inline-block;
}
</style>